package component;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class Tag {
	private String name;
	private String text;
	private Map map;

	public Tag(String name) {
		this.name = name;
	}

	public String openTag() {
		StringBuffer buffer = new StringBuffer();
		if (name == null || "".equals(name)) {
			throw new IllegalArgumentException("名称为空");
		}
		buffer.append("<").append(name);
		return buffer.toString();
	}

	private String setAttribute(String attrName, String value) {
		StringBuffer buffer = new StringBuffer();
		if (attrName == null || "".equals(attrName)) {
			throw new IllegalArgumentException("属性名为空");
		}
		if (value != null && !"".equals(value)) {
			buffer.append(" ").append(attrName).append("=\"").append(value)
					.append("\"");
		}

		return buffer.toString();
	}

	public Tag setAttribute(Map<String, String> map) {
		this.map = map;
		return this;
	}

	public String contrutor() {
		Set entries = map.entrySet();
		Iterator iterator = entries.iterator();
		StringBuffer html = new StringBuffer();
		html.append(openTag());
		while (iterator.hasNext()) {
			Map.Entry<String, String> entry = (Map.Entry) iterator.next();
			String key = entry.getKey();
			String value = entry.getValue();
			html.append(setAttribute(key, value));
		}
		html.append(setEnd());
		html.append(text == null ? "" : text);
		html.append(closeTag());
		return html.toString();
	}

	public String setEnd() {
		return ">";
	}


	public String closeTag() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("</").append(name).append(">");
		return buffer.toString();
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}
	@Override
	public String toString() {
		return contrutor();
	}

}
